package com.example.controller;

import com.example.dao.CronMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;

/**
* 定时任务开启与关闭
*/
@Slf4j
@RestController
@RequestMapping("/quartz/task")
public class DynamicTaskController {

   @Autowired
   private CronMapper cronMapper ;

   @Autowired
   private ThreadPoolTaskScheduler threadPoolTaskScheduler;

   private ScheduledFuture<?> future1;

   @Bean
   public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
       return new ThreadPoolTaskScheduler();
   }

   @GetMapping("/startCron1")
   public ResponseEntity<String> startCron1() {

       future1 = threadPoolTaskScheduler.schedule(new Runnable() {
           @Override
           public void run() {
               System.out.println("执行动态定时任务002: " + LocalDateTime.now().toLocalTime());
           }
       }, new Trigger() {
           @Override
           public Date nextExecutionTime(TriggerContext triggerContext) {
               return new CronTrigger(cronMapper.getCron(2)).nextExecutionTime(triggerContext);
           }
       });

       System.out.println("DynamicTask.startCron1()");

       return ResponseEntity.ok("startCron1成功");

   }

   @GetMapping("/stopCron1")
   public ResponseEntity<String> stopCron1() {
       if (future1 != null) {
           future1.cancel(true);
       }
       System.out.println("DynamicTask.stopCron1()");
       return ResponseEntity.ok("startCron1停止");
   }


}